#include "mini2440Messagescreensave.h"
#include <QBasicTimer>
#include <QList>
#include <QImage>
#include <QDir>
#include <QPainter>
#include <QPaintEvent>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <QDebug>


class MessageScreenSavePrivate
{
public:
    MessageScreenSavePrivate();

    int currentSlide;
    int slideInterval;
    QBasicTimer interSlideTimer;
    QStringList imagePaths;

    void showNextSlide();
};



MessageScreenSavePrivate::MessageScreenSavePrivate()
{
    currentSlide = 0;
    slideInterval = 10000; // Default to 10 sec interval
}


void MessageScreenSavePrivate::showNextSlide()
{
    currentSlide++;
    if (currentSlide >= imagePaths.size())
      currentSlide = 0;
}



MessageScreenSave::MessageScreenSave(QWidget* parent) :
    QWidget(parent)
{
    d = new MessageScreenSavePrivate;

    setAttribute(Qt::WA_StaticContents, true);
    setAttribute(Qt::WA_OpaquePaintEvent, true);
    setAttribute(Qt::WA_NoSystemBackground, true);

    setMouseTracking(true);
}


MessageScreenSave::~MessageScreenSave()
{
    delete d;
}


void MessageScreenSave::addImageDir(QString dirName)
{
    QDir dir(dirName);

    QStringList fileNames = dir.entryList(QDir::Files | QDir::Readable, QDir::Name);

    for (int i=0; i<fileNames.count(); i++)
        d->imagePaths << dir.absoluteFilePath(fileNames[i]);
}

void MessageScreenSave::addImage(QString filename)
{
    d->imagePaths << filename;
}


void MessageScreenSave::clearImages()
{
    d->imagePaths.clear();
}


void MessageScreenSave::startShow()
{
    d->interSlideTimer.start(d->slideInterval, this);
    d->showNextSlide();
    update();
}


void MessageScreenSave::stopShow()
{
    d->interSlideTimer.stop();
}


int MessageScreenSave::slideInterval()
{
    return d->slideInterval;
}

void MessageScreenSave::setSlideInterval(int val)
{
    d->slideInterval = val;
}

QString MessageScreenSave::getPassword()
{
  return m_password;
}

void MessageScreenSave::setPassword(QString password)
{
  m_password = password;
}

void MessageScreenSave::timerEvent(QTimerEvent* event)
{
    Q_UNUSED(event);
    d->showNextSlide();
    update();
}


void MessageScreenSave::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, false);

    if (d->imagePaths.size() > 0) {
        QPixmap slide = QPixmap(d->imagePaths[d->currentSlide]);
        QSize slideSize = slide.size();
        QSize scaledSize = QSize(qMin(slideSize.width(), size().width()),
            qMin(slideSize.height(), size().height()));
        if (slideSize != scaledSize)
            slide = slide.scaled(scaledSize, Qt::KeepAspectRatio);

        QRect pixmapRect(qMax( (size().width() - slide.width())/2, 0),
                         qMax( (size().height() - slide.height())/2, 0),
                         slide.width(),
                         slide.height());

        if (pixmapRect.top() > 0) {
            // Fill in top & bottom rectangles:
            painter.fillRect(0, 0, size().width(), pixmapRect.top(), Qt::black);
            painter.fillRect(0, pixmapRect.bottom(), size().width(), size().height(), Qt::black);
        }

        if (pixmapRect.left() > 0) {
            // Fill in left & right rectangles:
            painter.fillRect(0, 0, pixmapRect.left(), size().height(), Qt::black);
            painter.fillRect(pixmapRect.right(), 0, size().width(), size().height(), Qt::black);
        }

        painter.drawPixmap(pixmapRect, slide);

    } else
        painter.fillRect(event->rect(), Qt::black);
}

void MessageScreenSave::keyPressEvent(QKeyEvent* event)
{
    //    qDebug() << event->key() << "   "
    //             << event->type() << "   "
    //             << QEvent::KeyRelease << "   "
    //             << QEvent::KeyPress ;
    QWaitCondition sleep;
    QMutex mutex;

    if (m_currentPassword.length() >= PASSSWORD_LENGTH && event->key() != Qt::Key_Enter && m_key_0_count == 0)
        return;
    switch(event->key())
    {
    case Qt::Key_NumLock:
        if (m_key_0_count == 3)
        {
            m_currentPassword.remove(m_currentPassword.length()-1,1);
            m_currentPassword.append('2');
        }
        m_key_0_count = 0;
        break;
    case KEYPAD_1:
        if (!m_key_0_count)
            m_currentPassword.append('1');
        m_key_0_count++;
        break;
    case KEYPAD_3:
        m_currentPassword.append('3');
        break;
    case KEYPAD_4:
        m_currentPassword.append('4');
        break;
    case KEYPAD_5:
        m_currentPassword.append('5');
        break;
    case KEYPAD_6:
        m_currentPassword.append('6');
        break;
    case KEYPAD_7:
        m_currentPassword.append('7');
        break;
    case KEYPAD_8:
        m_currentPassword.append('8');
        break;
    case KEYPAD_9:
        m_currentPassword.append('9');
        break;
    case KEYPAD_0:
        m_currentPassword.append('0');
        break;
    case KEYPAD_ENTER:
        if (m_currentPassword == m_password)
        {
            m_wrongcount = 0;
            emit openDoor();
            //QMessageBox::information(this,"open the door","ok");
        }
        else
        {
            if (!m_currentPassword.isEmpty())
            {
                //QMessageBox::critical(this,"open the door","wrong");
                m_wrongcount++;
                if (m_wrongcount == 3)
                {
                    emit wrongpass();
                    m_wrongcount = 0;
                    //qDebug() << "wrong pass, log to server";
                }
            }
            else
            {
                if (mode)
                {
                    mode = false;
                }
                else
                {
                    if (event->type() == QEvent::KeyPress)
                    {
                        mode = true;
                        emit ringTheBell();
                        qDebug() << 1;
                        sleep.wait(&mutex,1000);   // two seconds
                        qDebug() << 2;
                        emit stopRingTheBell();
                    }
                }
            }
        }

        m_currentPassword.clear();
        break;
    default:
        break;
    }
    qDebug() << m_currentPassword;
    event->ignore();
    return;
}

void MessageScreenSave::mousePressEvent(QMouseEvent* event)
{
    Q_UNUSED(event);
    emit readNewMessage();
}


void MessageScreenSave::mouseReleaseEvent(QMouseEvent* event)
{
    Q_UNUSED(event);
    emit readNewMessage();
}


void MessageScreenSave::showEvent(QShowEvent * event )
{
    Q_UNUSED(event);
#ifndef QT_NO_CURSOR
    setCursor(Qt::BlankCursor);
#endif
}
